package com.sx.service.utils.sender.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.sx.service.utils.sender.ISenderService;
import com.sx.service.utils.sender.SenderType;
import com.sx.service.utils.sender.model.SenderRequest;
import com.sx.service.utils.sender.model.SmsRequest;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;

/**
 * @author AdinZ
 * @date 2020/11/11 18:09
 */
public class SmsServiceImpl implements ISenderService {

    private final JSONObject config;
    private final DefaultAcsClient client;

    public SmsServiceImpl(JSONObject config){
        this.config=config;
        DefaultProfile profile = DefaultProfile.getProfile(config.getString("regionId"), config.getString("accessKeyId"), config.getString("accessSecret"));
        this.client = new DefaultAcsClient(profile);
    }

    @Override
    public boolean sender(SenderRequest senderRequest) {
        if (senderRequest instanceof SmsRequest) {
            SmsRequest sms = (SmsRequest) senderRequest;
            CommonRequest request = new CommonRequest();
            request.setSysMethod(MethodType.POST);
            request.setSysDomain("dysmsapi.aliyuncs.com");
            request.setSysVersion("2017-05-25");
            request.setSysAction("SendSms");
            request.putQueryParameter("RegionId", config.getString("regionId"));
            request.putQueryParameter("PhoneNumbers", StringUtils.isEmpty(sms.getAreaCode()) ? sms.getTo() : sms.getAreaCode() + sms.getTo());
            request.putQueryParameter("SignName", config.getString("signName"));
            request.putQueryParameter("TemplateCode", sms.getTemplateCode());
            request.putQueryParameter("TemplateParam", sms.getContent());
            try {
                CommonResponse response = client.getCommonResponse(request);
                if (response.getHttpStatus() == 200) {
                    return true;
                } else {
                    throw new RuntimeException(response.getData());
                }
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        } else throw new RuntimeException("数据类型不正确");
    }

    @Override
    public SenderType getType() {
        return SenderType.SMS;
    }
}
